<template>
  <div class="view-account">
    <div class="view-account-header"></div>
    <div class="view-account-container">
      <div class="view-account-top">
        <div class="view-account-top-logo">
          <img src="~@/assets/images/account-logo.png" alt="" />
        </div>
        <div class="view-account-top-desc">Naive Ui Admin中台前端/设计解决方案</div>
      </div>
      <div class="view-account-form">
        <n-tabs
          default-value="userNameLogin"
          size="large"
          justify-content="space-evenly"
          @update:value="changeTab"
        >
          <n-tab-pane name="userNameLogin" tab="用户名密码登录">
            <n-form
              ref="formRef"
              label-placement="left"
              size="large"
              :model="formInline"
              v-if="tabName == 'userNameLogin'"
              :rules="rules"
            >
              <n-form-item path="username">
                <n-input v-model:value="formInline.username" placeholder="请输入用户名">
                  <template #prefix>
                    <n-icon size="18" color="#808695">
                      <PersonOutline />
                    </n-icon>
                  </template>
                </n-input>
              </n-form-item>
              <n-form-item path="password">
                <n-input
                  v-model:value="formInline.password"
                  type="password"
                  showPasswordOn="click"
                  placeholder="请输入密码"
                >
                  <template #prefix>
                    <n-icon size="18" color="#808695">
                      <LockClosedOutline />
                    </n-icon>
                  </template>
                </n-input>
              </n-form-item>
              <n-form-item path="isCaptcha">
                <div class="w-full">
                  <mi-captcha
                    width="384"
                    theme-color="#2d8cf0"
                    :logo="logo"
                    @success="onAuthCode"
                  />
                </div>
              </n-form-item>
            </n-form>
          </n-tab-pane>
          <n-tab-pane name="mobileLogin" tab="短信验证码登录">
            <n-form
              ref="mobileFormRef"
              label-placement="left"
              size="large"
              v-if="tabName == 'mobileLogin'"
              :model="formInline"
              :rules="mobileFormRules"
            >
              <n-form-item path="mobile">
                <n-input v-model:value="formInline.mobile" placeholder="请输入手机号码">
                  <template #prefix>
                    <n-icon size="18" color="#808695">
                      <PersonOutline />
                    </n-icon>
                  </template>
                </n-input>
              </n-form-item>
              <n-form-item path="smsCode">
                <n-input v-model:value="formInline.smsCode" placeholder="请输入短信验证码">
                  <template #prefix>
                    <n-icon size="18" color="#808695">
                      <MailOutline />
                    </n-icon>
                  </template>
                </n-input>
                <n-button style="margin-left: 5px" :disabled="btnDisabled" @click="sendMsgCode">{{
                  btnText
                }}</n-button>
              </n-form-item>
            </n-form>
          </n-tab-pane>
        </n-tabs>
        <n-grid :cols="1" class="default-color">
          <n-gi>
            <div class="flex justify-between">
              <div class="flex-initial">
                <n-checkbox v-model:checked="autoLogin">自动登录</n-checkbox>
              </div>
              <div class="flex-initial order-last">
                <a href="javascript:" @click="findPwd">忘记密码</a>
              </div>
            </div>
          </n-gi>
        </n-grid>
        <n-form-item>
          <n-button type="primary" @click="handleSubmit" size="large" :loading="loading" block>
            登录
          </n-button>
        </n-form-item>
        <n-grid :cols="1">
          <n-gi>
            <div class="flex view-account-other">
              <div class="flex-initial">
                <span>其它登录方式</span>
              </div>
              <div class="flex-initial mx-2">
                <a href="javascript:" @click="toWechatLogin">
                  <n-icon size="24" color="#2d8cf0">
                    <LogoWechat />
                  </n-icon>
                </a>
              </div>
              <div class="flex-initial mx-2">
                <a href="javascript:" @click="toAlipayLogin">
                  <n-icon size="24" color="#2d8cf0">
                    <LogoAlipay />
                  </n-icon>
                </a>
              </div>
              <div class="flex-initial mx-2">
                <a href="javascript:" @click="toGiteeLogin">
                  <n-icon size="24" color="#2d8cf0">
                    <svg
                      t="1634026098340"
                      class="icon"
                      viewBox="0 0 1024 1024"
                      version="1.1"
                      xmlns="http://www.w3.org/2000/svg"
                      p-id="1772"
                      width="200"
                      height="200"
                    >
                      <path
                        d="M512 1024C229.248 1024 0 794.752 0 512S229.248 0 512 0s512 229.248 512 512-229.248 512-512 512z m259.168-568.896h-290.752a25.28 25.28 0 0 0-25.28 25.28l-0.032 63.232c0 13.952 11.296 25.28 25.28 25.28h177.024a25.28 25.28 0 0 1 25.28 25.28v12.64a75.84 75.84 0 0 1-75.84 75.84h-240.224a25.28 25.28 0 0 1-25.28-25.28v-240.192a75.84 75.84 0 0 1 75.84-75.84h353.92a25.28 25.28 0 0 0 25.28-25.28l0.064-63.2a25.312 25.312 0 0 0-25.28-25.312H417.184a189.632 189.632 0 0 0-189.632 189.6v353.952c0 13.952 11.328 25.28 25.28 25.28h372.928a170.656 170.656 0 0 0 170.656-170.656v-145.376a25.28 25.28 0 0 0-25.28-25.28z"
                        p-id="1773"
                        fill="#d81e06"
                      />
                    </svg>
                  </n-icon>
                </a>
              </div>
              <div class="flex-initial" style="margin-left: auto">
                <router-link to="/register">
                  <a href="javascript:">注册账号</a>
                </router-link>
              </div>
            </div>
          </n-gi>
        </n-grid>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, onMounted } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { useMessage } from 'naive-ui';
  import { ResultEnum } from '@/enums/httpEnum';
  import { sendSmsCode } from '@/api/system/user';
  import { useUserStore } from '../../store/modules/user';
  import { alipayLogin, getToken, giteeLogin } from '@/api/system/social';
  import { storage } from '@/utils/Storage';
  import logo from '@/assets/images/logo.png';
  import {
    PersonOutline,
    LockClosedOutline,
    LogoGithub,
    LogoFacebook,
    MailOutline,
    LogoAlipay,
    LogoWechat,
  } from '@vicons/ionicons5';
  import { ACCESS_TOKEN, CURRENT_USER, IS_LOCKSCREEN } from '@/store/mutation-types';
  const formRef = ref();
  const message = useMessage();
  const loading = ref(false);
  const autoLogin = ref(true);
  const count = ref(60);
  const tabName = ref('userNameLogin');
  const btnDisabled = ref(false);
  const btnText = ref('获取验证码');
  const mobileFormRef = ref();
  const formInline = reactive({
    username: 'admin',
    password: '12345678',
    mobile: '',
    code: '',
    isCaptcha: false,
  });

  const rules = {
    username: { required: true, message: '请输入用户名', trigger: 'blur' },
    password: { required: true, message: '请输入密码', trigger: 'blur' },
    isCaptcha: {
      required: true,
      type: 'boolean',
      trigger: 'change',
      message: '请点击按钮进行验证码校验',
      validator: (_, value) => value === true,
    },
  };
  const mobileFormRules = {
    mobile: {
      required: true,
      message: '请输入手机号码',
      trigger: 'blur',
      validator: (rule, value) => {
        const reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
        return new Promise((resolve, reject) => {
          if (value == null) {
            reject(Error('请输入手机号码'));
          } else if (!reg.test(value)) {
            reject(Error('请输入正确的手机号码'));
          } else {
            resolve();
          }
        });
      },
    },
    smsCode: { required: true, message: '请输入短信验证码', trigger: 'blur' },
  };
  const userStore = useUserStore();

  const router = useRouter();
  const route = useRoute();

  const handleSubmit = (e) => {
    e.preventDefault();
    if (tabName.value == 'userNameLogin') {
      formRef.value.validate(async (errors) => {
        if (!errors) {
          message.loading('登录中...');
          loading.value = true;
          const response = await userStore.login(formInline, tabName.value);
          loginSuccess(response);
        } else {
          message.error('请填写完整信息，并且进行验证码校验');
        }
      });
    } else if (tabName.value == 'mobileLogin') {
      mobileFormRef.value.validate(async (errors) => {
        if (!errors) {
          message.loading('登录中...');
          loading.value = true;
          const response = await userStore.login(formInline, tabName.value);
          loginSuccess(response);
        } else {
          message.error('请填写完整信息，并且进行验证码校验');
        }
      });
    }
  };
  const toAlipayLogin = () => {
    alipayLogin().then((res) => {
      location.href = res;
    });
  };
  const toGiteeLogin = () => {
    giteeLogin().then((res) => {
      location.href = res;
    });
  };
  const toWechatLogin = () => {
    message.success('暂未开发，敬请期待');
  };
  const relateLogin = () => {
    let q = route.query;
    let error = q.error;
    if (error !== '' && error !== undefined) {
      message.error(error);
    }
    let related = q.related;
    let tokenKey = q.tokenKey;
    if (related && related === '1' && tokenKey) {
      getToken(tokenKey).then((data) => {
        const ex = 7 * 24 * 60 * 60 * 1000;
        storage.set(ACCESS_TOKEN, data, ex);
        storage.set(CURRENT_USER, data, ex);
        storage.set(IS_LOCKSCREEN, false);
        userStore.setToken(data);
        const toPath = decodeURIComponent((route.query?.redirect || '/') as string);
        message.success('登录成功！');
        router.replace(toPath).then((_) => {
          if (route.name == 'login') {
            router.replace('/');
          }
        });
      });
    }
  };
  onMounted(() => {
    relateLogin();
  });
  const loginSuccess = (response) => {
    if (response.code == ResultEnum.SUCCESS) {
      const toPath = decodeURIComponent((route.query?.redirect || '/') as string);
      message.success('登录成功！');
      router.replace(toPath).then((_) => {
        if (route.name == 'login') {
          router.replace('/');
        }
      });
    } else {
      message.error(response.message || '登录失败');
      loading.value = false;
    }
  };
  const register = () => {
    console.log(router);
    router.replace('/register');
  };
  const findPwd = () => {
    router.replace('/findPwd');
  };
  const downCount = () => {
    if (count.value == 0) {
      btnText.value = '获取验证码';
      btnDisabled.value = false;
      count.value = 60;
      return;
    } else {
      btnText.value = count.value + '秒后重试';
      count.value--;
      btnDisabled.value = true;
    }
    setTimeout(() => {
      downCount();
    }, 1000);
  };
  const sendMsgCode = () => {
    if (formInline.mobile == '') {
      message.error('请输入手机号码');
      return;
    }
    sendSmsCode(formInline.mobile).then((res) => {
      if (res) {
        message.success('发送成功');
        downCount();
      }
    });
  };
  const changeTab = (value) => {
    tabName.value = value;
  };
  const onAuthCode = () => {
    formInline.isCaptcha = true;
  };
</script>

<style lang="less" scoped>
  .view-account {
    display: flex;
    flex-direction: column;
    height: 100vh;
    overflow: auto;

    &-container {
      flex: 1;
      padding: 32px 0;
      width: 384px;
      margin: 0 auto;
    }

    &-top {
      padding: 32px 0;
      text-align: center;

      &-desc {
        font-size: 14px;
        color: #808695;
      }
    }

    &-other {
      width: 100%;
    }

    .default-color {
      color: #515a6e;

      .ant-checkbox-wrapper {
        color: #515a6e;
      }
    }
  }

  @media (min-width: 768px) {
    .view-account {
      background-image: url('../../assets/images/login.svg');
      background-repeat: no-repeat;
      background-position: 50%;
      background-size: 100%;
    }

    .page-account-container {
      padding: 32px 0 24px 0;
    }
  }
</style>
